'use strict';
import React from "react";
import {
    ListView,
    View,
    Text,
    Image,
    TouchableOpacity,
    StyleSheet,
    RefreshControl,
    ActivityIndicator
} from "react-native";
import WithTogether from "../Pages/WithTogetherDetails";
import HelpToBuyDetails from "../Pages/HelpToBuyDetails";
import QuestionDetailsPage from "../Pages/QuestionDetailsPage";
import TravelsDetails from "../Pages/TravelsDetails";
import ImageViewer from "../Pages/ImageViewer";
import objectImageViewer from "../Pages/objectImageViewer";
import Global from "../Commom/GlobalConst";
import FoundAPIService from "../Commom/FoundAPIService";
import DateUtil from "../Commom/DateUtil";
import Toast from '../Utils/toast';
const width = Global.Const.size.width;
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F2F3F5'
    },
    row: {
        marginTop: 10,
        padding: 10,
        flex: 1,
        backgroundColor: 'white'
    },
    rowTop: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    rowAvatar: {
        width: 40,
        height: 40,
        marginRight: 10,
        borderRadius: 20,
    },
    rowBottom: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginLeft: 48,
        marginTop: 5,
        alignItems: 'center'
    },
    rowBtnBox: {
        width: 70,
        backgroundColor: '#38D68B',
        borderRadius: 5,
        alignItems: 'center',
        justifyContent: 'center',
        paddingTop: 5,
        paddingBottom: 5,
    },
    rowBtn: {
        fontSize: 14,
        color: 'white',
    },
    travelBox: {
        flex: 1,
        marginLeft: 40,
        flexDirection: 'row',
        borderColor: '#F2F3F5',
        borderWidth: 1,
        padding: 5,
        marginTop: 5,
        backgroundColor: '#F5F5F5',
        borderRadius: 3
    },
    travelText: {
        fontSize: 14,
        flex: 1,
        color: Global.FontColor.DimGray
    },
    image: {
        width: (width - 89) / 4,
        height: (width - 89) / 4,
        marginTop: 3,
        marginRight: 5,
    },
    avatarName: {
        fontSize: 15,
        color: Global.FontColor.DimGray
    }
});


class FoundPageTabNewPage extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (r1, r2) => r1 !== r2
            }),
            flag: false,
            searchText: '',
            isRefreshing: false,
            record_count: 1,
            page: 1,
            newDataList: [],
        };
        this.NewSearch = this.NewSearch.bind(this);
        this.initData = this.initData.bind(this);
    }

    componentDidMount() {
        this.initData();
    }

    NewSearch(searchText) {
        if (searchText.length > 0) {
            this.setState({
                searchText: searchText,
                isRefreshing: true,
            });
            FoundAPIService.searchDynamic(searchText, '0', 1).then((ret)=> {
                this.setState({
                    isRefreshing: false,
                    newDataList: ret.result,
                    record_count: ret.record_count,
                    page: Number(ret.page),
                    dataSource: this.state.dataSource.cloneWithRows(ret.result),
                });
            }).catch((err)=> {
                this.setState({
                    isRefreshing: false,
                    newDataList: [],
                    record_count: 1,
                    page: 1,
                    dataSource: this.state.dataSource.cloneWithRows([]),
                });
            });
        } else {
            this.initData();
            this.setState({
                searchText: ''
            });
        }

    }

    initData() {
        if (this.state.searchText.length == 0) {
            this.setState({
                isRefreshing: true
            });
            FoundAPIService.dynamic('0', 1).then((ret)=> {
                this.setState({
                    flag: true,
                    isRefreshing: false,
                    newDataList: ret.result,
                    record_count: ret.record_count,
                    page: Number(ret.page),
                    dataSource: this.state.dataSource.cloneWithRows(ret.result),
                });
            }).catch((err)=> {

            });
        } else {
            FoundAPIService.searchDynamic(this.state.searchText, '0', 1).then((ret)=> {
                this.setState({
                    flag: true,
                    isRefreshing: false,
                    newDataList: ret.result,
                    record_count: ret.record_count,
                    page: Number(ret.page),
                    dataSource: this.state.dataSource.cloneWithRows(ret.result),
                });
            }).catch((err)=> {

            });
        }
    }

    onRefresh() {
        if (this.state.searchText.length == 0) {
            this.setState({
                isRefreshing: true
            });
            FoundAPIService.dynamic('0', 1).then((ret)=> {
                this.setState({
                    isRefreshing: false,
                    newDataList: ret.result,
                    record_count: ret.record_count,
                    page: Number(ret.page),
                    dataSource: this.state.dataSource.cloneWithRows(ret.result),
                });
                Toast.show('刷新成功');
            }).catch((err)=> {

            });
        } else {
            FoundAPIService.searchDynamic(this.state.searchText, '0', 1).then((ret)=> {
                this.setState({
                    isRefreshing: false,
                    newDataList: ret.result,
                    record_count: ret.record_count,
                    page: Number(ret.page),
                    dataSource: this.state.dataSource.cloneWithRows(ret.result),
                });
                Toast.show('刷新成功');
            }).catch((err)=> {

            });
        }
    }

    loadMoreData() {

        if (this.state.page < this.state.record_count) {
            this.setState({
                isRefreshing: true,
            });
            if (this.state.searchText.length == 0) {
                FoundAPIService.dynamic('0', this.state.page + 1).then((ret)=> {
                    let wanjian = [];
                    wanjian = this.state.newDataList;
                    for (var i = 0; i < ret.result.length; i++) {
                        wanjian.push(ret.result[i])
                    }
                    this.setState({
                        isRefreshing: false,
                        newDataList: wanjian,
                        record_count: ret.record_count,
                        page: Number(ret.page),
                        dataSource: this.state.dataSource.cloneWithRows(wanjian),
                    });
                    Toast.show('加载成功');
                }).catch((err)=> {

                });
            } else {
                FoundAPIService.searchDynamic(this.state.searchText, '0', this.state.page + 1).then((ret)=> {
                    let wanjian = [];
                    wanjian = this.state.newDataList;
                    for (var i = 0; i < ret.result.length; i++) {
                        wanjian.push(ret.result[i])
                    }
                    this.setState({
                        isRefreshing: false,
                        newDataList: wanjian,
                        record_count: ret.record_count,
                        page: Number(ret.page),
                        dataSource: this.state.dataSource.cloneWithRows(wanjian),
                    });
                    Toast.show('加载成功');
                }).catch((err)=> {

                });
            }
        } else {
            if (this.state.page != 1) {
                Toast.show('木有更多数据');
            }
        }
    }

    goToPage(row) {
        let navigator = this.props.navigator;
        let name = 'WithTogetherDetail';
        let component = WithTogether;
        switch (row.type) {
            case '0':
                name = 'WithTogetherDetail';
                component = WithTogether;
                break;
            case '1':
                name = 'QuestionDetailsPage';
                component = QuestionDetailsPage;
                break;
            case '2':
                name = 'HelpToBuyDetails';
                component = HelpToBuyDetails;
                break;
            case '3':
                name = 'TravelsDetails';
                component = TravelsDetails;
                break;
        }
        navigator.push({
            name,
            component,
            passProps: {
                ID: row.id
            }
        });
    }


    render() {
        return (
            <View style={styles.container}>
                {this.state.flag ? <ListView
                    style={styles.container}
                    dataSource={this.state.dataSource}
                    renderRow={(row, rowID) => this._renderRow(row, rowID)}
                    onEndReached={() => this.loadMoreData()}
                    onEndReachedThreshold={100}
                    enableEmptySections={true}
                    initialListSize={6}
                    refreshControl={
                    <RefreshControl
                        refreshing={this.state.isRefreshing}
                        onRefresh={() => {this.onRefresh();}}
                        colors={['#4CAF50', '#4CAF50', '#4CAF50', '#4CAF50']}
                    />
                }
                /> :
                    <View style={{flex:1,backgroundColor:'#F5F5F5'}}><View
                        style={{position: 'absolute',top:-65,left:0,width:Global.Const.size.width,height:Global.Const.size.height,backgroundColor:null,alignItems:'center',justifyContent:'center'}}>
                        <View
                            style={{backgroundColor:'#333333',borderRadius:5, alignItems: 'center',justifyContent: 'center',width:80,height:80}}>
                            <ActivityIndicator
                                animating={this.state.animating}
                                style={{ alignItems: 'center',justifyContent: 'center'}}
                                size="large"/>
                            <Text style={{color:'white'}}>加载中...</Text>
                        </View>
                    </View></View>}

            </View>

        )
    }

    goToImageViewer(images) {
        this.props.navigator.push({
            name: 'ImageViewer',
            component: ImageViewer,
            passProps: {
                source: images,
            }
        })
    }

    goToObjectImageViewer(images) {
        this.props.navigator.push({
            name: 'objectImageViewer',
            component: objectImageViewer,
            passProps: {
                source: images,
            }
        })
    }

    _renderRow(row, rowID) {
        let content = null;
        let typeText = '';
        let btnText = '';
        switch (row.type) {
            case '0':
                typeText = '自驾约伴';
                btnText = '参加';
                break;
            case '1':
                typeText = '有问必答';
                btnText = '有赏回答';
                break;
            case '2':
                typeText = '帮购';
                btnText = '帮我买';
                break;
            case '3':
                typeText = '游记';
                content = <View style={styles.travelBox}>
                    <Image style={styles.image} source={{uri:row.images[0]}}/>
                    <Text numberOfLines={3}
                          style={styles.travelText}>{row.content}</Text>
                </View>;
                break;
        }
        let images = row.images;
        let initiated_list = row.initiated_list;
        let time = DateUtil.dateStr(row.add_time);
        return (
            <TouchableOpacity onPress={() => this.goToPage(row)}>
                <View style={styles.row}>
                    <View style={styles.rowTop}>
                        <Image source={{uri:row.avatar}} style={styles.rowAvatar}/>
                        <Text style={styles.avatarName}>{row.user_name}</Text>
                    </View>
                    {
                        content === null ?
                            <View style={{
                                marginLeft: 48,
                                marginTop: 5,
                            }}>
                                <Text
                                    style={{fontSize: 15, color: Global.FontColor.LightGrey,lineHeight: 25}}>{row.content}</Text>
                                <View style={{flexDirection: 'row', marginTop: 10, flexWrap: 'wrap'}}>
                                    {
                                        images ?
                                            images.map((item, index) => {
                                                return (
                                                    <TouchableOpacity
                                                        style={styles.image}
                                                        key={'row' + (rowID + index)}
                                                        onPress={() => this.goToImageViewer(images)}
                                                    >
                                                        <Image style={styles.image}
                                                               source={{uri:item}}/>
                                                    </TouchableOpacity>
                                                )
                                            }) : null
                                    }
                                    {
                                        initiated_list ?
                                            initiated_list.map((item, index) => {
                                                return (
                                                    <TouchableOpacity key={'row' + (rowID + index)}
                                                                      onPress={() => this.goToObjectImageViewer(initiated_list)}
                                                    >
                                                        <Image style={styles.image}
                                                               source={{uri:item.images}}/>
                                                    </TouchableOpacity>
                                                )
                                            }) : null
                                    }
                                </View>
                            </View>
                            : content
                    }
                    <View style={styles.rowBottom}>
                        <Text style={{fontSize: 12,color: Global.FontColor.DarkGray}}>{typeText}</Text>
                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
                            <Text
                                style={{fontSize: 12, marginRight: 5,color: Global.FontColor.DarkGray}}>{time}</Text>
                            {
                                btnText ?
                                    <TouchableOpacity
                                        onPress={() => this.goToPage(row)}
                                        style={styles.rowBtnBox}>
                                        <Text style={styles.rowBtn}>{btnText}</Text>
                                    </TouchableOpacity> : <View/>
                            }
                        </View>
                    </View>
                </View>
            </TouchableOpacity >
        )
    }

}

export default FoundPageTabNewPage;